package zjitc.net.Dao.imp;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import zjitc.net.Dao.UserDao;
import zjitc.net.Daomain.User;
import zjitc.net.utils.JDBCUtils;

import java.util.List;

public class UserDaoImp implements UserDao {
  JdbcTemplate template= new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<User> FindAll() {
        String sql="select * from user";
        List<User> list=template.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return list;
    }

    @Override
    public User FindUsernameAndPassword(String username, String password) {
       String sql="select * from user where username=? and password=?";
        List<User> list=template.query(sql,new BeanPropertyRowMapper<User>(User.class),username,password);
        if (list.size()==0){
            return null;
        }
        if (list.size()==1){
            return list.get(0);
        }
        return null;
    }

    @Override
    public int add(User user) {
        String sql = "INSERT INTO user(username,password,sex,email,tel) VALUES(?,?,?,?,?)";
        Object [] objects={user.getUsername(),user.getPassword(),user.getSex(),user.getEmail(),user.getTel()};
        int add=template.update(sql,objects);
        return add;
    }

    @Override
    public int update(User user) {
       String sql="update user set username=?,password=?,email=?,sex=?,tel=? where=id=?";
        Object [] objects={user.getUsername(),user.getPassword(),user.getSex(),user.getEmail(),user.getTel(),user.getId()};
        int update=template.update(sql,objects);
        return update;
    }

    @Override
    public int delete(int index) {
        String sql="delete from user where id=?";
        int delete=template.update(sql,index);
        return delete;
    }
}
